<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use app\common\model\Config as ConfigsModel;
use app\common\model\BookAccount as BookAccountModel;
use think\Validate;
use think\Db;
use think\facade\Log;

class BookExtraDraw extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $updateTime = 'time';
 
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        
        $list = $this->field('bed.*, type.name as typeName, param.name as paramName, vs.season_name as season, vd.bmmc as dep, sc.name as center')
            ->alias('bed')
            ->distinct(true)
            ->join('zl_book_extra_draw_detail detail', 'bed.id = detail.draw_id')
            ->join('zl_student_info vb', 'detail.xh = vb.xh') 
            ->leftjoin('zl_view_get_seasons vs', 'vs.season_id = bed.season')
            ->leftjoin('zl_view_get_depts vd', 'vd.bmdm = bed.dep_id')
            ->leftjoin('zl_sub_center sc', 'sc.id = bed.sub_center_id')
            ->leftjoin('zl_student_type type', 'type.id = bed.type_id')
            ->leftjoin('zl_student_type_params param', 'param.id = bed.param_id')
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->paginate($limit);

        $data1 = $this->field('bed.*, type.name as typeName, param.name as paramName, vs.season_name as season, vd.bmmc as dep, sc.name as center')
            ->alias('bed')
            ->distinct(true)
            ->join('zl_book_extra_draw_detail detail', 'bed.id = detail.draw_id')
            ->join('zl_student_info vb', 'detail.xh = vb.xh') 
            ->leftjoin('zl_view_get_seasons vs', 'vs.season_id = bed.season')
            ->leftjoin('zl_view_get_depts vd', 'vd.bmdm = bed.dep_id')
            ->leftjoin('zl_sub_center sc', 'sc.id = bed.sub_center_id')
            ->leftjoin('zl_student_type type', 'type.id = bed.type_id')
            ->leftjoin('zl_student_type_params param', 'param.id = bed.param_id')
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->select();
        
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = count($data1);
        $re['data'] = $data;
        return $re;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    public function getKeyList()
    {
        $list = $this->alias('a')
                ->field("concat(a.year, '-', case when a.season = 1 then '春季' when a.season = 3 then '秋季' end, '-', c.name, '-', d.name) as keyName")
                ->leftjoin('zl_student_type c', 'c.id = a.type_id')
                ->leftjoin('zl_student_type_params d', 'd.id = a.param_id')->select()->toArray();
 
                $nameList = [];
                foreach ($list as $key => $val) {
                    $nameList[] = $val['keyName'];
                }
                
                return $nameList;
    }

    public function getBookDetail($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['bed.year', 'eq', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['bed.season', 'eq', $post['season']];
        }
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['bed.id', 'eq', $post['id']];
        }
  
        $list = $this->field('bi.*, stbr.book_num, stbr.price, stbr.book_disc')
            ->alias('bed')
            ->join('zl_student_type_book_rel stbr', 'bed.year = stbr.plan_year and bed.season = stbr.plan_season and bed.type_id = stbr.type_id and bed.param_id = stbr.param_id')
            ->join('zl_book_info bi', 'stbr.book_id = bi.id') 
            ->where($where)
            ->order('bi.id')
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    public function getStudentDetailExport($post)
    {
        $where = [];
        
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['a.id', 'eq', $post['id']];
        }
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['c.xh', 'eq', $post['xh']];
        }
        if(isset($post['xm']) && $post['xm'] != ""){
            $where[] = ['c.xm', 'like', '%' . $post['xm'] . '%'];
        }
  
        $list = $this->field('a.year,d.season_name as season,e.bmmc as dep,f.name as center,a.grade,g.name as typeName,h.name as paramName,b.id, c.xh, c.xm, i.zymc, j.bjmc')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_info c', 'b.xh = c.xh') 
            ->leftjoin('zl_view_get_seasons d', 'd.season_id = a.season')
            ->leftjoin('zl_view_get_depts e', 'e.bmdm = a.dep_id')
            ->leftjoin('zl_sub_center f', 'f.id = a.sub_center_id')
            ->leftjoin('zl_student_type g', 'g.id = a.type_id')
            ->leftjoin('zl_student_type_params h', 'h.id = a.param_id')
            ->leftjoin('zlzhsf.pzydm i', 'b.zydm = i.zydm') 
            ->leftjoin('zlzhsf.pbjdm j', 'b.bjdm = j.bjdm') 
            ->where($where)
            ->order('c.xh')->select()->toArray();
               //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

               if (count($list) > 0) {
                $result['status'] = true;
                $result['msg']    = '导出成功';
                $result['data']   = $list;
                return $result;
            } else {
                //失败，导出失败
                return $result;
            }
            
    }

    public function getStudentDetail($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['bed.year', 'eq', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['bed.season', 'eq', $post['season']];
        }
        if(isset($post['id']) && $post['id'] != ""){
            $where[] = ['a.id', 'eq', $post['id']];
        }
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['c.xh', 'eq', $post['xh']];
        }
        if(isset($post['xm']) && $post['xm'] != ""){
            $where[] = ['c.xm', 'like', '%' . $post['xm'] . '%'];
        }
  
        $list = $this->field('b.id, c.xh, c.xm, d.zymc, e.bjmc')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_info c', 'b.xh = c.xh') 
            ->leftjoin('zlzhsf.pzydm d', 'b.zydm = d.zydm') 
            ->leftjoin('zlzhsf.pbjdm e', 'b.bjdm = e.bjdm') 
            ->where($where)
            ->order('c.xh')
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    public function hasdraw($year, $season, $type_id, $xh)
    {
        $xh = $this->field('c.xh')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->where(['year' => $year, 'season' => $season, 'type_id' => $type_id, 'b.xh' => $xh])
            ->find();

        if($xh) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 批量插入
     * @param $post
     * @return array
     */
    public function extradrawSave($post)
    {
        $result = [
            'status' => false,
            'msg'    => '预发放失败',
            'data'   => []
        ];

        // 变量
        $new_id = $this->getMaxID();  // 最新ID
        $year = $post['year'];
        $season = $post['season'];
        $dep_id = $post['dep_id'];
        $sub_center_id = $post['draw_sub_center_id'];
        $operid = session('manage')['id'];

        $condition = []; 
        $condition[] = ['year', 'eq', $year];
        $condition[] = ['season', 'eq', $season];
        $condition[] = ['dep_id', 'eq', $dep_id];
  
        if(isset($sub_center_id) && $sub_center_id != ""){
            $condition[] = ['sub_center_id', 'eq', $sub_center_id]; 
        }
        
        // 判断是否重复的非计划发放
        // $info = $this->where($condition)->count();
        // if($info){
        //     $result['status'] = false;
        //     $result['msg'] = '所选条件下存在科教中心的发放记录！';   
        //     return $result;
        // }

        // 生成发放记录
        // 根据年度、季度、部/院、科教中心查询
        $model = new Common();
        $list = $model->query("call extraDraw('".$operid."','".$year."','".$season."','".$dep_id."','".$sub_center_id."');");
        if(!count($list) && !count($list[0])){
            $result['status'] = false;
            $result['msg'] = '所选条件下没有对应的非计划发放信息！';   
            return $result;
        }
  
        $bookExtraDrawDetail = new BookExtraDrawDetail();
        // 非计划发放数据
        foreach($list[0] as $item) {
            $iData       = [
                'id'            => $new_id,
                'operId'        => $operid,
                'year'          => $year,
                'season'        => $season,
                'type_id'       => $item['type_id'],
                'param_id'      => $item['param_id'],
                'dep_id'        => $item['plan_dep_id'],
                'sub_center_id' => $item['subcenter_id'],
                'grade'         => $item['plan_grade'],
                'num'           => $item['num'],
                'time'          => $item['time'],
                'is_dy'         => $item['isdy'],
                'dy_num'        => $item['dy_num'],
            ];

            $this->insert($iData);
    
            // 明细
            $xhList = [];
            $detailList = [];
            $model = new Common();
            $xhlist = $model->query("call extraDrawDetail('".$operid."','".$year."','".$season."','".$item['plan_dep_id']."','".$item['subcenter_id']."','".$item['type_id']."','".$item['param_id']."','".$item['plan_grade']."');");
            if(count($xhlist) && count($xhlist[0])){
                foreach($xhlist[0] as $xhItem) {
                    $detailList[] = array(
                            'draw_id'=>$new_id, 
                            "xh"=>$xhItem['xh'],
                            "zydm"=>$xhItem['zydm'],
                            "bjdm"=>$xhItem['bjdm'],
                            "dir"=>$xhItem['dir'],
                        );
                    $xhList[] = $xhItem['xh'];
                }
            } 
            $bookExtraDrawDetail->saveAll($detailList, false);

            // 设置账表状态
            // $whereUpdate[] = ['xh', 'in', $xhList];
            // $whereUpdate[] = ['year', 'eq', $year];
            // $whereUpdate[] = ['season', 'eq', $season];
            // $bookAccountModel = new BookAccountModel();
            // $bookAccountModel->save(['status'=>0], $whereUpdate);
            
            $new_id++;
        }

        $result['status'] = true;
        $result['msg']    = '发放成功'; 
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }


    // 非计划发放：根据ID获取明细
    public function getinfobyid($post)
    {
        $data = $this->field('bed.*, vs.season_name as season, vd.bmmc as dep, vsp.zymc as specialty, vc.plan_class_name as class, vdr.name as dir')
                ->alias('bed')
                ->leftjoin('zl_view_get_seasons vs', 'vs.season_id = bed.season')
                ->leftjoin('zl_view_get_depts vd', 'vd.bmdm = bed.dep_id')
                ->leftjoin('zl_view_get_specicalties vsp', 'vsp.zydm = bed.specialty_id and vsp.bmdm = bed.dep_id ')
                ->leftjoin('zl_view_get_classes vc', 'vc.plan_class_id = bed.class_id and vc.bmdm = bed.dep_id and vc.zydm = bed.specialty_id ')
                ->leftjoin('zl_view_get_dirs vdr', 'vdr.id = bed.dir')
                ->where('bed.id',$post["id"])->find();
        return $data;
    }
  
    // where搜索条件（预发放）
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['year', 'eq', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['season', 'eq', $post['season']];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['dep_id', 'eq', $post['dep_id']];
        }
        if(isset($post['sub_center_id']) && $post['sub_center_id'] != ""){
            $where[] = ['sub_center_id', 'eq', $post['sub_center_id']];
        }
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['detail.xh', 'eq', $post['xh']];
        }
        if(isset($post['xm']) && $post['xm'] != ""){
            $where[] = ['vb.xm', 'like', '%'.$post['xm'].'%'];
        }
        if(isset($post['is_dy']) && $post['is_dy'] != ""){
            $where[] = ['is_dy', 'eq', $post['is_dy']];
        }
        
        $where[] = ["num", "gt", 0];  # 数量为正数
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['bed.year', 'bed.season', 'bed.dep_id', 'bed.sub_center_id', 'bed.id ASC'];
        return $result;
    }
 
    /**
     * @param $list
     *
     * @return mixed
     */
    public function tableFormat($list)
    {
        foreach($list as &$val){
            $val['time'] = getTime($val['time']); 
            // $val['season'] = getSeason($val['season']);
            // $val['dir'] = getDir($val['dir']);
        }
        return $list;
    }
 
    // 非计划发放：重置打印状态 1->0
    public function bookextraresetprintstatus($data)
    {
        $result = [
            'status' => false,
            'msg'    => '重置失败',
            'data'   => [],
        ];

        $ids_arr = explode(",", $data['ids']);
        $dataList = [];
        foreach($ids_arr as $val) {
            $dataList[] = array('id'=>$val, "is_dy"=>"0");
        }
        # 重置成功
        if($this->isUpdate(true)->saveAll($dataList))
        {
            $result['status'] = true;
            $result['msg']    = '重置成功';
        }
        return $result;
    }

    // 非计划发放：打印状态改变 0->1
    public function bookextraprintstatus($data)
    {
        $result = [
            'status' => false,
            'msg'    => '打印失败',
            'data'   => [],
        ];

        $ids_arr = explode(",", $data['ids']);
        $dataList = [];
        foreach($ids_arr as $val) {
            $dataList[] = array('id'=>$val, "is_dy"=>"1");
        }
        # 打印成功
        if($this->isUpdate(true)->saveAll($dataList))
        {
            $result['status'] = true;
            $result['msg']    = '打印成功';
        }
        return $result;
    }
    
    // 获取最新的id
    public function getMaxID()
    {
        $pre_id = date("Ymd");  # 编号前缀
        $condition = [['id', "like",  $pre_id."%"]];  # 必须是二维数组
        $res = $this->where($condition)->max('id');
        if($res){
			$num = (int)substr($res, -4);  # 截取最后4位
            $num++;
			$res = $pre_id.sprintf("%04d", $num);  # 补足4位
        }
        else{
            $res = $pre_id."0001";
        }
        return $res;
    }
}